package com.tbit.uqbike.webmanager.util;

import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.ResultMsg;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author chenmengran
 * @Description: TODO
 * @date 2019\4\8 000814:48
 */
@SuppressWarnings("unused")
@Slf4j
public class MsgSendUtil {
    public static String sendUrl = "http://sim.tbit.com.cn/identity/sendShortMsg.do";
    public static String returnUrl = "http://sim.tbit.com.cn/identity/polling.do";
    public static String sendSerNo = "UQ-889";
    public static String sendSecret = "tbit-uqbike-uqbike-tbit-uqbike-bit-00369696";

    static {
        Properties props = new Properties();
        try {
            props.load(new InputStreamReader(MsgSendUtil.class.getClassLoader().getResourceAsStream("msgSend.properties"), "UTF-8"));
            String sendUrl = props.getProperty("sendUrl");
            String returnUrl = props.getProperty("returnUrl");
            String sendSerNo = props.getProperty("sendSerNo");
            String sendSecret = props.getProperty("sendSecret");
        } catch (Exception e) {
            LogUtil.warn("加载校准Memcached配置文件失败");
        }
    }

    /**
     * 发送短信控制
     */
    @SuppressWarnings("unchecked")
    public static String sendMsg(String machineNO, Integer type) {
        Map params = new HashMap();
        params.put("serNo", sendSerNo);
        params.put("machineNo", machineNO);
        params.put("type", type);
        params.put("secret", sendSecret);
        LogUtil.info("短信发送[" + "设备编号: " + machineNO + "控制类型: " + type + "]");
        String result = APIStore.doPost(sendUrl, APIStore.urlencode(params));
        ResultMsg resultMsg = JsonUtils.json2Obj(result, ResultMsg.class);
        if (resultMsg.getRet() != 1) {
            throw new BaseException(resultMsg.getMsg());
        }

        return resultMsg.getData();
    }

    /**
     * 轮询
     */
    public static String polling(String serial) {
        Map params = new HashMap();
        params.put("serial", serial);
        params.put("serNo", sendSerNo);
        params.put("secret", sendSecret);
        String result = APIStore.doPost(returnUrl, APIStore.urlencode(params));
        ResultMsg resultMsg = JsonUtils.json2Obj(result, ResultMsg.class);
        if (resultMsg.getRet() != 1) {
            throw new BaseException(resultMsg.getMsg());
        }
        return resultMsg.getData();
    }

}
